package demo.issuetracker.dao.jpa;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.util.UUID;

import javax.persistence.Entity;
import javax.persistence.Id;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;

/**
 * Represents an uploaded file
 */
@Entity
public class UploadedFile {
    private String contentType;
    private String fileName;

    /**
     * Unique identifier of this activity.
     */
    @Id
    private String id;

    private Blob blob;

    public String getContentType() {
        return contentType;
    }

    public String getFileName() {
        return fileName;
    }

    public String getId() {
        return id;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public void setBlob(InputStream stream) {
        try {
            this.blob = Hibernate.createBlob(stream);
        } catch (IOException ex) {
            throw new RuntimeException("Error while converting uploaded file to blob", ex);
        }
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setId(String id) {
        this.id = id;
    }

    public static UploadedFile newInstance() {
        UploadedFile uploadedFile = new UploadedFile();
        uploadedFile.setId(UUID.randomUUID().toString());
        return uploadedFile;
    }

    public Blob getBlob() {
        return blob;
    }

    public void setBlob(Blob blob) {
        this.blob = blob;
    }

    public void update(String fileName, String contentType, InputStream inputStream) {
        if (StringUtils.isNotBlank(fileName)) {
            setFileName(fileName);
            setContentType(contentType);
            setBlob(inputStream);
        }
    }
}// clickframes::version=4161402787::clickframes